package com.bigknow.appstore.proxy.handler.register;

import com.bigknow.appstore.proxy.cache.ICacheManager;
import com.bigknow.appstore.proxy.handler.base.BaseInboundHandler;
import com.bigknow.appstore.proxy.log.ILogWriter;
import com.bigknow.appstore.proxy.server.IProxyServer;
import com.bigknow.appstore.proxy.timetask.impl.LastRequestVoRemoveWorker;
import com.bigknow.appstore.proxy.util.HandlerVariables;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpMessage;

import java.net.InetSocketAddress;

/**
 * 如果proxyMeta 的 useLastRequest为true将开启此功能，当uri和user，filter Handler都通过了后
 * <br>才能调用此handler,这个地方将requestVO存储入HandlerVariables.lastRequestVos
 * <br>配合FindLastRequestHandler一起使用
 * Created by chaos on 2016/9/19.
 */
@ChannelHandler.Sharable
public class LastRequestForSameConnHandler extends BaseInboundHandler {

    public LastRequestForSameConnHandler(IProxyServer proxyServer, ICacheManager cacheManager, ILogWriter writer) {
        super(proxyServer, cacheManager, writer);
    }

    @Override
    public void read(ChannelHandlerContext ctx, FullHttpMessage msg) throws Exception {
        String id = ((InetSocketAddress) ctx.channel().remoteAddress()).getAddress().getHostAddress();
        HandlerVariables.lastRequestVos.put(id, HandlerVariables.currentRequestVoLocal.get());
        ((LastRequestVoRemoveWorker) proxyServer.getTimeWorkerMap().get(LastRequestVoRemoveWorker.class.getName()))
                .addLastRequestTime(id);
        ctx.fireChannelRead(msg);
    }
}
